package com.zfb.videoscript.core

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.graphics.Path
import android.graphics.Rect
import android.view.accessibility.AccessibilityNodeInfo
import kotlinx.coroutines.delay
import kotlin.random.Random

class ActionController(
    private val service: AccessibilityService,
    private val nodeLocator: NodeLocator,
    private val logManager: LogManager
) {
    // 点赞动作
    suspend fun performLike(config: NodeConfig): Boolean {
        try {
            // 先尝试通过节点点击
            val likeNode = nodeLocator.findNode(config.likeButton)
            if (likeNode != null) {
                val rect = Rect()
                likeNode.getBoundsInScreen(rect)
                return performClick(rect.centerX().toFloat(), rect.centerY().toFloat())
            }
            
            // 如果找不到节点，使用固定坐标
            config.likeButton.bounds?.let { (x, y) ->
                return performClick(x.toFloat(), y.toFloat())
            }
            
            logManager.logOperation("点赞失败", "未找到点赞按钮")
            return false
        } catch (e: Exception) {
            logManager.logOperation("点赞异常", e.message ?: "未知错误")
            return false
        }
    }

    // 滑动动作
    suspend fun performSwipe(
        startX: Float = 540f,
        startY: Float = 1600f,
        endX: Float = 540f,
        endY: Float = 400f,
        duration: Long = 300
    ): Boolean {
        try {
            val path = Path().apply {
                moveTo(startX, startY)
                lineTo(endX, endY)
            }
            
            val gesture = GestureDescription.Builder()
                .addStroke(GestureDescription.StrokeDescription(path, 0, duration))
                .build()

            var success = false
            service.dispatchGesture(gesture, object : AccessibilityService.GestureResultCallback() {
                override fun onCompleted(gestureDescription: GestureDescription?) {
                    success = true
                }
                override fun onCancelled(gestureDescription: GestureDescription?) {
                    success = false
                }
            }, null)

            // 等待手势完成
            delay(duration + 100)
            return success
        } catch (e: Exception) {
            logManager.logOperation("滑动异常", e.message ?: "未知错误")
            return false
        }
    }

    // 检查红包按钮
    fun checkRedPacket(config: NodeConfig): Boolean {
        return nodeLocator.findNode(config.redPacketButton) != null
    }

    // 随机点击
    private suspend fun performClick(x: Float, y: Float): Boolean {
        val path = Path().apply {
            moveTo(x, y)
            lineTo(x, y)
        }
        
        val gesture = GestureDescription.Builder()
            .addStroke(GestureDescription.StrokeDescription(path, 0, 100))
            .build()

        var success = false
        service.dispatchGesture(gesture, object : AccessibilityService.GestureResultCallback() {
            override fun onCompleted(gestureDescription: GestureDescription?) {
                success = true
            }
            override fun onCancelled(gestureDescription: GestureDescription?) {
                success = false
            }
        }, null)

        delay(150)
        return success
    }

    // 添加随机性
    fun addRandomness(value: Int, range: Int): Int {
        return value + Random.nextInt(-range, range + 1)
    }

    // 获取节点文本
    fun getNodeText(node: AccessibilityNodeInfo?): String {
        return node?.text?.toString() ?: ""
    }

    // 获取节点描述
    fun getNodeDescription(node: AccessibilityNodeInfo?): String {
        return node?.contentDescription?.toString() ?: ""
    }

    // 检查节点是否可点击
    fun isNodeClickable(node: AccessibilityNodeInfo?): Boolean {
        return node?.isClickable == true
    }

    // 检查节点是否可见
    fun isNodeVisible(node: AccessibilityNodeInfo?): Boolean {
        return node?.isVisibleToUser == true
    }

    // 获取节点在屏幕上的位置
    fun getNodeBounds(node: AccessibilityNodeInfo?): Rect? {
        if (node == null) return null
        val rect = Rect()
        node.getBoundsInScreen(rect)
        return rect
    }
} 